package org.feng.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.feng.client.request.BaiduRequest;
import org.feng.client.response.BaiDuAiGetAccessTokenResponse;
import org.feng.client.response.BaiDuResponse;
import org.feng.config.BaiDuAiProperties;
import org.feng.service.OkHttpService;
import org.json.JSONObject;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author feng
 */
@Getter
@Slf4j
public abstract class BaiDuAiClient {

    protected final static String ACCESS_TOKEN = "access_token";

    protected static final ObjectMapper MAPPER = new ObjectMapper();

    @Resource
    protected BaiDuAiProperties baiDuAiProperties;

    @Setter
    protected String accessToken;

    @Resource
    protected OkHttpService okHttpService;

    /**
     * 获取 AccessToken
     */
    public BaiDuAiGetAccessTokenResponse generateAccessToken() {
        String accessTokenUrl = String.format(baiDuAiProperties.getAccessTokenFormatterUrl(), baiDuAiProperties.getClientId(), baiDuAiProperties.getClientSecret());
        Request request = new Request.Builder()
                .url(accessTokenUrl)
                .build();
        try (Response response = okHttpService.newCall(request)) {
            String json = response.body().string();
            return MAPPER.readValue(json, BaiDuAiGetAccessTokenResponse.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 识别图片
     *
     * @param url   请求url
     * @param image 图片内容
     * @return 识别结果
     */
    public String recognizeImage(String url, String image, Map<String, Object> params) {
        if (!CollectionUtils.isEmpty(params)) {
            List<String> paramFields = new ArrayList<>();
            params.forEach((fieldName, fieldValue) -> {
                if (fieldValue != null) {
                    paramFields.add(fieldName + "=" + fieldValue);
                }
            });
            String joinedParams = String.join("&", paramFields);
            url = url + "?" + joinedParams;
        }

        log.info("请求url={}", url);
        // 构建请求体
        RequestBody requestBody = RequestBody.Companion.create("image=" + image, OkHttpService.X_WWW_FORM_URLENCODED_MEDIA_TYPE);
        Request request = new Request.Builder()
                .header(OkHttpService.CONTENT_TYPE, OkHttpService.X_WWW_FORM_URLENCODED)
                .url(url)
                .post(requestBody)
                .build();

        try (Response response = okHttpService.newCall(request)) {
            return response.body().string();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Map<String, Object> generateParamMapWithToken() {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("access_token", accessToken);
        return params;
    }
}
